package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import jdk.nashorn.internal.ir.IfNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;
import java.util.Map;

import static com.alipay.api.AlipayConstants.SIGN_TYPE;

/**
 * @author Sanmier
 * @create 2020-12-21 19:47
 */
@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private PaymentService paymentService;

    //接写一个@ResponseBody  注解直接将这个字符串显示到页面
    @RequestMapping("submit/{orderId}")
    @ResponseBody
    public String submitAlipay(@PathVariable Long orderId){

        String from = "";
        try {
            //调用方法即可
            from  = alipayService.createaliPay(orderId);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return from;
    }


    //同步回调
    @RequestMapping("callback/return")
    public String callbackPayment(){
        return "redirect:"+ AlipayConfig.return_order_url;
    }


    //异步会调
    @RequestMapping("callback/notify")
    @ResponseBody
    public String callbackNotify(@RequestParam Map<String,String> paramMap){
        System.out.println("来人了  接待客人");
        //验签  成功返回success
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramMap, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.sign_type);  //调用SDK验证签名
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        String outTradeNo = paramMap.get("out_trade_no");

        //获取交易状态
        String tradeStatus = paramMap.get("trade_status");
        //根据这个参数参训交易记录  如果能够的到  说明一致！
        //验证out_trade_no
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
        if (paymentInfo==null){
            //验证参数失败。。
            return "failure";
        }
        //totalamout，app_id
        //判断是否验签成功
        if (signVerified){
            //TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus) ){

                //细节处理  需要做一个判断这个交易记录不能是关闭  或者是支付状态
                if (paymentInfo.getPaymentStatus().equals("CLOSED")||
                paymentInfo.getPaymentStatus().equals("PAID")){
                    return "failure";
                }

                //更新一下交易记录状态
                paymentService.paySuccess(outTradeNo,PaymentType.ALIPAY.name(),paramMap);

                //返回支付成功
                return "success";
            }

        }else {
            //TODO 验证失败则记录异常记录，并在response中返回failure。


        }
        //本身在支付宝异步回调的参数中能够获取  out_trade_no;total_amount;seller_id;app_id
        //根据条件查询出在支付时  我们提交的数据  验证价格
        //在支付宝的业务通知中  只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时  支付宝才会认定为买家付款成功

        //失败 failure
        return "success";
    }


    //退款
    @RequestMapping("refund/{orderId}")
    @ResponseBody
    public Result refund(@PathVariable Long orderId){
        //调用退款方法
        boolean flag = alipayService.refund(orderId);
        return Result.ok(flag);
    }


    // 根据订单Id关闭订单
    @GetMapping("closePay/{orderId}")
    @ResponseBody
    public Boolean closePay(@PathVariable Long orderId){
        Boolean aBoolean = alipayService.closePay(orderId);
        return aBoolean;
    }


    // 查看是否有交易记录
    @RequestMapping("checkPayment/{orderId}")
    @ResponseBody
    public Boolean checkPayment(@PathVariable Long orderId){
        //调用退款接口
        Boolean flag = alipayService.checkPayment(orderId);
        return flag;
    }


    //查询PaymentInfo 数据接口
    @GetMapping("getPaymentInfo/{outTradeNo}")
    @ResponseBody
    public PaymentInfo getPaymentInfo(@PathVariable String outTradeNo){
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
        if (paymentInfo!=null){
            return paymentInfo;
        }
        return null;
    }
}
